package com.cloudcc.mobile.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.im.UIControl;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.OrmManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.presenter.ContactPresenter;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.util.SystemUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.dynamic.DynamicOneListActivity;
import com.cloudcc.mobile.view.main.fragment.IContactUserInfo;

import butterknife.Bind;


public class NewUserInfoActivity extends BaseActivity implements IContactUserInfo{
	//xingming
	@Bind(R.id.tv_newuser_name_value)
	TextView tv_newuser_name_value;
	@Bind(R.id.tv_newuser_juese_value)
	TextView tv_newuser_juese_value;
	@Bind(R.id.tv_newuser_jiandang_value)
	TextView tv_newuser_jiandang_value;
	//邮箱
	@Bind(R.id.tv_newuser_thname_value)
	TextView tv_newuser_thname_value;
	@Bind(R.id.tv_newuser_bumen_value)
	TextView tv_newuser_bumen_value;
	@Bind(R.id.tv_newuser_dianhua_value)
	TextView tv_newuser_dianhua_value;
	@Bind(R.id.tv_newuser_phone_value)
	TextView tv_newuser_phone_value;
	//头像右边
	@Bind(R.id.user_email)
	TextView user_email;
	@Bind(R.id.user_name)
	TextView user_name;
	
	
	@Bind(R.id.btn_newuser_dianhua)
	TextView btn_newuser_dianhua;
	@Bind(R.id.btn_newuser_xiaoxi)
	TextView btn_newuser_xiaoxi;
	@Bind(R.id.btn_newuser_guanzhu)
	TextView btn_newuser_guanzhu;
	@Bind(R.id.btn_newuser_tiezi)
	TextView btn_newuser_tiezi;
	
	@Bind(R.id.user_follow_newuser)
	ImageView user_follow_newuser;
	@Bind(R.id.backuser)
	ImageView backuser;
	private String userId;
	private boolean isFromNetWork = false;
	private ContactPresenter mContactPresenter;
	private ChatUser user;
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private boolean mBos;
	@Override
	public void init(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.init(savedInstanceState);
		if ("en".equals(mEns)) {
			mBos = true;
		}else{
			mBos = false;
		}
		mContactPresenter = new ContactPresenter((IContactUserInfo) NewUserInfoActivity.this);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			userId = bundle.getString("userId", "");
		}
		if (TextUtils.isEmpty(userId)) {
			if (mBos) {
				Toast.makeText(mContext, "Get user details failed...", 0).show();
			}else{
				Toast.makeText(mContext, "获取用户详情失败...", 0).show();
			}
			
			finish();
			return;
		}
		initdata();
		addlistener();
		
	}
	private void initdata() {
		// TODO Auto-generated method stub
		refreshUserfromCache();
		refreshUserInfoFromNet();
	}

	/**
	 * 通过sortmode的数据库 刷新 早晚得删除
	 */
	private void refreshUserfromCache() {
		CoworkerEntity contactEntity = ContactsManager.getInstance()
				.getContactById(userId);
		if (contactEntity != null) {
			user = ContactsManager.getInstance().covert2ChatUser(contactEntity);
			refreshUIAndData();
		}
	}
	private void refreshUIAndData() {
		if (user == null) {
			return;
		}
		if (mBos) {
			if(user.isIsfollowme()){
				btn_newuser_guanzhu.setText("Has been concerned");
				btn_newuser_guanzhu.setBackgroundColor(Color.rgb(51, 153, 255));
			}else{
				btn_newuser_guanzhu.setText("attention");
				btn_newuser_guanzhu.setBackgroundColor(Color.rgb(255, 255, 255));
			}
		}else{
			if(user.isIsfollowme()){
				btn_newuser_guanzhu.setText("已关注");
				btn_newuser_guanzhu.setBackgroundColor(Color.rgb(51, 153, 255));
			}else{
				btn_newuser_guanzhu.setText("关注");
				btn_newuser_guanzhu.setBackgroundColor(Color.rgb(255, 255, 255));
			}
		}
		
		tv_newuser_bumen_value.setText("");//部门
		tv_newuser_dianhua_value.setText(user.getPhone());
		tv_newuser_jiandang_value.setText(user.getProfilename());//建档
		tv_newuser_juese_value.setText(user.getRolename());//角色
		user_name.setText(user.getName());
		tv_newuser_phone_value.setText(user.getMobile());
		user_email.setText(user.getEmail());//邮箱
		// 头像 TODO

		String url = UrlTools.getTopImage(userId);
		user_follow_newuser.postInvalidate();
		UserUtils.setLogoRound_z(url, user_follow_newuser,
				UserUtils.getBackGroudColorByUserIdHash(userId, mContext),
				UserUtils.getNickRowName(user.getName()), mContext);

	}
//	private void refreshFollowStatus() {
//		if (user != null) {
//			user_follow_newuser
//					.setImageResource(user.isIsfollowme() ? R.drawable.guanzhut
//							: R.drawable.guanzhuf);
//		}
//
//	}
	/**
	 * 刷新用户
	 */
	private void refreshUserInfoFromNet() {
		isFromNetWork = true;
		mContactPresenter.getUserInfoChatter(userId);
	}
	private void addlistener() {
		// TODO Auto-generated method stub
		backuser.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		//拨打电话
				btn_newuser_dianhua.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if("".equals(user.getMobile())){
							if("".equals(user.getPhone())){
								if (mBos) {
									Toast.makeText(mContext, "The phone number is empty", 1).show();
								}else{
									Toast.makeText(mContext, "手机号码为空", 1).show();
								}
								
							}else{
								SystemUtils.sendCall(mContext, user.getPhone());
							}
						}else{
								SystemUtils.sendCall(mContext, user.getMobile());
						}
					}
				});
				//发消息
				btn_newuser_xiaoxi.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if("cc201307019DXlPd701".equals(RunTimeManager.getInstance().getOrgId())){
							Toast.makeText(NewUserInfoActivity.this,"您好，体验版本无法使用聊天功能",1).show();
						}else {
							if (user != null) {
								SharedPreferences pref = NewUserInfoActivity.this.getSharedPreferences(
										"data", 0);
								SharedPreferences.Editor editor = pref.edit();
								editor.clear();

								editor.commit();
								if (UserUtils.isMe(userId)) {
									if (mBos) {
										Toast.makeText(mContext, "I'm sorry I can not chat with myself...", 0).show();
									} else {
										Toast.makeText(mContext, "对不起不能自己跟自己聊天...", 0).show();
									}

								} else {
									UIControl.openChatUI(mContext, ContactsManager.getInstance().encodeHXuserName(userId),
											user.getName(), false);
								}
							}
						}
					}
				});
				//关注
				btn_newuser_guanzhu.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (UserUtils.isMe(userId)) {
							if (mBos) {
								Toast.makeText(mContext, "I can not afford to focus on myself...",0).show();
							}else{
								Toast.makeText(mContext, "对不起不能自己关注自己...",0).show();
							}
							
						}else{
						new OtherPresenter().followPeople(userId, user.isIsfollowme(),
								new RequestListener() {

									@Override
									public void onSuccess(Object arg0) {
										user.setIsfollowme(!user.isIsfollowme());
										if (mBos) {
											if(user.isIsfollowme()){
												btn_newuser_guanzhu.setText("Has been concerned");
												btn_newuser_guanzhu.setBackgroundColor(Color.rgb(51, 153, 255));
											}else{
												btn_newuser_guanzhu.setText("attention");
												btn_newuser_guanzhu.setBackgroundColor(Color.rgb(255, 255, 255));
											}
										}else{
											if(user.isIsfollowme()){
												btn_newuser_guanzhu.setText("已关注");
												btn_newuser_guanzhu.setBackgroundColor(Color.rgb(51, 153, 255));
											}else{
												btn_newuser_guanzhu.setText("关注");
												btn_newuser_guanzhu.setBackgroundColor(Color.rgb(255, 255, 255));
											}
										}
										
									}

									@Override
									public void onFailure(ErrorInfo arg0) {
									}
								});	
					}
					}
				});
				
				//历史帖子
				btn_newuser_tiezi.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (user == null) {
							return;
						}
						Intent intent = new Intent(mContext, DynamicOneListActivity.class);
						intent.putExtra("userName", user.getName());
						intent.putExtra("userId", TextUtils.isEmpty(userId)?user.getUserid():userId);
						mContext.startActivity(intent);
					}
				});
	}
	@Override
	public int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.newact_userinfo;
	}
	@Override
	public void onGettedUser(DataEvent<ChatUser> event) {
		// TODO Auto-generated method stub
		if (event.isError()) {
			return;
		}
		user = event.getData();
		if (isFromNetWork) {
			CoworkerEntity contactEntity = ContactsManager.covert2ContactEntity(user);
			OrmManager.getManager().getOrm().save(contactEntity);
			isFromNetWork = false;
		}
		
		refreshUIAndData();
	}
}
